package com.example.rice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.rice.common.CustomException;
import com.example.rice.common.R;
import com.example.rice.dto.DishDto;
import com.example.rice.entity.Category;
import com.example.rice.entity.Dish;
import com.example.rice.entity.DishFlavor;
import com.example.rice.entity.Setmeal;
import com.example.rice.service.CategoryService;
import com.example.rice.service.DishFlavorService;
import com.example.rice.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * 菜品相关控制器
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询菜品相关信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        //转化成DTO
        Page<DishDto> dishDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //进行分页查询
        dishService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();
        //将数据列表中的分类id拿去查询分类信息，然后封装好分类返回到页面
        List<DishDto> list = records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            //进行对象拷贝
            BeanUtils.copyProperties(item,dishDto);
            //获取列表中每个数据的分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        //清除菜品缓存部分数据
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功！");
    }


    /**
     * 根据id查询菜品信息
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> getOne(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 更新菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品的缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        //清除修改部分数据
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功！");
    }

    /**
     * 更改菜品出售状态接口
     * @param
     * @return
     */
    @PostMapping ("/status/{state}")
    public R<String> updateStatus(@PathVariable int state,@RequestParam List<Long> ids){
        int count = 0;
        //统计一下选择的套餐是否全部处于需要更改状态
        for (Long i:ids) {
            Dish dish = dishService.getById(i);
            if (dish.getStatus()==state){
                count++;
            }
        }
        //如果是更改状态直接抛出业务异常，提示用户无需更改
        if(count == ids.size()){
            if (state == 1){
                throw new CustomException("您选择的菜品已经全部处于启售状态无需更改！");
            }else {
                throw new CustomException("您选择的菜品已经全部处于停售状态无需更改！");
            }
        }
        for (Long i:ids) {
            Dish dish = dishService.getById(i);
            dish.setStatus(state);
            dishService.updateById(dish);
            //清除菜品缓存部分数据
            String key = "dish_"+dish.getCategoryId()+"_1";
            redisTemplate.delete(key);
        }
        return R.success("更改成功");
    }

    /**
     * 删除批量删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@PathParam("ids") String ids){
        String[] idsList = ids.split(",");
        for (String i:idsList) {
            DishDto dishDto = dishService.getByIdWithFlavor(Long.valueOf(i));
            //根据dto里面的id去清理口味相关的记录
            LambdaQueryWrapper<DishFlavor>  queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
            dishFlavorService.remove(queryWrapper);
            //根据id去删除dish表上记录
            dishService.removeById(Long.valueOf(i));
            //清除菜品缓存部分数据
            String key = "dish_"+dishDto.getCategoryId()+"_1";
            redisTemplate.delete(key);
        }

        return R.success("删除成功");
    }


    /**
     * 根据分类id查询菜品信息,新增套餐页面使用接口
     * @param dish
     * @return
     */

//    @GetMapping("list")
//    public R<List<Dish>> list(Dish dish){
//        //构成条件查询
//        LambdaQueryWrapper<Dish> queryWrapper =new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId() !=null, Dish::getCategoryId,dish.getCategoryId());
//        //排除未启售的菜品
//        queryWrapper.eq(Dish::getStatus,1);
//        //添加排序条件
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }

    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList = null;
        //dish_(id)_1
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存
        dishDtoList  = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null){
            //查询如果存在，直接返回数据
            return R.success(dishDtoList);
        }
        //构成条件查询
        LambdaQueryWrapper<Dish> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() !=null, Dish::getCategoryId,dish.getCategoryId());
        //排除未启售的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        //将数据列表中的分类id拿去查询分类信息，然后封装好分类返回到页面
        dishDtoList = list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            //进行对象拷贝
            BeanUtils.copyProperties(item,dishDto);
            //获取列表中每个数据的分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //如果不存在进入数据库查询
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }

}
